/* 
 * Copyright (C) 2013, 2014 lex xiang
 *
 * file:	app/command.c
 * history:	2013 Juy 25 created by lex
 * comment:	
 */
#include <string.h>
#include <stdio.h>
#include "command.h"
#include "xmodem.h"
#include "boot.h"

struct cmd_desc_s cmd_cd_desc = {
	"go to directory!",
	"cd [directory]"
};
void cmd_cd(struct command_s *cmd, struct shell *sh)
{
	struct tty *tty = sh->tty;

	tty->op.dev_printf(tty, "command do cd argc = %d, argv[0] = %s, argv[1] = %s.\n", 
			   sh->argc, sh->argv[0], sh->argv[1]);
	return;
}

struct cmd_desc_s cmd_xmodem_desc = {
	"download or upload file through xmodem",
	"xmodem [download|upload] [image|bootloader]"
};
void cmd_xmodem(struct command_s *cmd, struct shell *sh)
{
	struct tty *tty = sh->tty;
	u32 *buf, len;
	u8 mode[32], type[32];

	if (!(buf = (u32 *)malloc(IMAGE_SIZE_MAX)))
		tty->op.dev_printf(tty, "No more vacancy to do download!\n");

	strcpy(type, sh->argv[1]);
	if (strcmp(type, "image") != 0 && strcmp(type, "bootloader") != 0) {
		tty->op.dev_printf(tty, "Unkonw argument: %s\n", sh->argv[1]);
		goto err;
	}

	if (strcmp(sh->argv[0], "download") == 0) {
		if (xmodem_download((u8 *)buf, sizeof(buf)) < 0) {
			tty->op.dev_printf(tty, "%s download error\n", type);
			goto err;
		}
	}
	else if (strcmp(sh->argv[0], "upload") == 0) {
		if (xmodem_upload((u8 *)buf, len) < 0) {
			tty->op.dev_printf(tty, "%s upload error\n", type);
			goto err;
		}
	}
	else {
		tty->op.dev_printf(tty, "Unkonw argument: %s\n", sh->argv[0]);
	}
err:
	free(buf);
	return;
}


struct command_s boot_cmd[] = {
	CMD_ENTRY(cd, root, root, &cmd_cd, &cmd_cd_desc),
	CMD_ENTRY(xmodem, root, root, &cmd_xmodem, &cmd_xmodem_desc),
};

